//
//  DownloadDetailViewController.m
//  UADE-Mobile
//
//  Created by Marcos Damian Pianelli on 10/6/11.
//  Copyright (c) 2011 DG. All rights reserved.
//

#import "DownloadDetailViewController.h"
#import "MBProgressHUD.h"

@implementation DownloadDetailViewController
@synthesize fileTitle, progressBar, fileInfo, urlRequest, webView, openInButton, connection, filepathDic, filePathURL, receivedData, suggestedFileName,fileSize, flipView, navWebView, navFileView;


MBProgressHUD * progressHUD;
BOOL isFlipped;
BOOL isRotated;
BOOL canFlip;

-(IBAction)flipViews{
    
    if (canFlip) {
        if(!isFlipped){
            
            if(isRotated)
                [webView setFrame:CGRectMake(0,0,480,320)];
            else   
                [webView setFrame:CGRectMake(0,0,320,480)];
            
            
            [UIView transitionFromView:navWebView toView:navFileView duration:0.55 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished){
                /* do something on animation completion */
            }];
            
            
            [UIView transitionFromView:flipView toView:webView duration:0.55 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished){
                /* do something on animation completion */
            }];
            
        }else{
            
            if(isRotated)
                [flipView setFrame:CGRectMake(0,0,480,320)];
            else   
                [flipView setFrame:CGRectMake(0,0,320,480)];
            
            
            
            [UIView transitionFromView:navFileView toView:navWebView duration:0.55 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished){
                /* do something on animation completion */
            }];
            
            
            [UIView transitionFromView:webView toView:flipView duration:0.55 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished){
                /* do something on animation completion */
            }];
            
        }
        
        isFlipped = !isFlipped;
        
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No se puede abrir" 
                                                        message:@"Tipo de archivo no soportado." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Aceptar"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
}


- (id)initWithNavigatorURL:(NSURL*)URL query:(NSDictionary*)query {
    
    self = [super initWithNibName:@"DownloadDetailViewController" bundle:nil];
    
    if (self) {
      
       /* navWebView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navWebView"]];
        navFileView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navFileView"]];
        */  
        isFlipped = false;
        canFlip = TRUE;
        self.fileInfo = query;
        //NSLog(@"%@", self.fileInfo);
        if([[self.fileInfo objectForKey:@"Extension"] isEqualToString:@".java"] ||
           [[self.fileInfo objectForKey:@"Extension"] isEqualToString:@".m"] ||
           [[self.fileInfo objectForKey:@"Extension"] isEqualToString:@".c"] ||
           [[self.fileInfo objectForKey:@"Extension"] isEqualToString:@".uml"] ||
           [[self.fileInfo objectForKey:@"Extension"] isEqualToString:@".zip"] ||
           [[self.fileInfo objectForKey:@"Extension"] isEqualToString:@".rar"]){
            canFlip = FALSE; 
        }
        self.title = [self.fileInfo objectForKey:@"Nombre"];
       
     
    }
    
    return self;
    
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma NSURLConnectionDownloadDelegate
/*- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL{
    
}

- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes{
    
    [self performSelectorOnMainThread:@selector(setProgress:) withObject:[NSNumber numberWithFloat:totalBytesWritten/expectedTotalBytes] waitUntilDone:FALSE];
    

    //[self.progressBar setProgress:totalBytesWritten/expectedTotalBytes animated:TRUE];

}

-(void)setProgress:(NSNumber*)progress{
    
    self.progressBar.progress = [progress floatValue];
    
}

- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes{
    
    
}*/

static UIDocumentInteractionController * docController;

-(IBAction)loadDocumentInteraction:(id)sender{

    if( self.filePathURL != nil ){
        docController = [UIDocumentInteractionController interactionControllerWithURL: self.filePathURL] ;
    
        docController.delegate = self;
        
        BOOL appsAvailable = [docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
        //NSLog(@"%@", appsAvailable?@"yes":@"no");
        if(!appsAvailable){
            [self flipViews];
        }
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    self.suggestedFileName = response.suggestedFilename;
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    [receivedData appendData:data];

    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    // Check & create directory
    NSString *path;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Files"];
	NSError *error;
    
	if (![[NSFileManager defaultManager] fileExistsAtPath:path])	//Does directory already exist?
	{
		if (![[NSFileManager defaultManager] createDirectoryAtPath:path
									   withIntermediateDirectories:NO
														attributes:nil
															 error:&error])
		{
			NSLog(@"Create directory error: %@", error);
		}
	}
    
    // Write file
    NSData *file;
	file = receivedData;
	paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Files"];
	path = [path stringByAppendingPathComponent:self.suggestedFileName];
    
    [[NSFileManager defaultManager] createFileAtPath:path
                                            contents:file
                                          attributes:nil];
    
    self.filePathURL = [NSURL fileURLWithPath:path];
    
    [self.filepathDic setObject:path  forKey:self.urlRequest];
    
    [[NSUserDefaults standardUserDefaults] setObject:self.filepathDic forKey:@"filePathDic"];

    
    NSURLRequest *request = [NSURLRequest requestWithURL:self.filePathURL];
    [self.webView loadRequest:request];

    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
    if (progressHUD != nil) {
        [self hideProgressHUD];
    }
   // if(!isFlipped)
   //     [self flipViews];

}




- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    return self.view.frame;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return self.view;
}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
    
}

#pragma mark - View lifecycle



- (void)webViewDidStartLoad:(UIWebView *)webView{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
    self.progressBar.hidden = true;
    [self hideProgressHUD];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"error: %@", error);
    [self hideProgressHUD];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initProgressHUD];

    // Do any additional setup after loading the view from its nib.
    self.progressBar.progress = 0;
    //[self.progressBar setProgress:0 animated:FALSE];
    self.progressBar.hidden = true;

    self.fileTitle.text = [NSString stringWithFormat:@"%@%@",[fileInfo objectForKey:@"Nombre"],[fileInfo objectForKey:@"Extension"]];
    self.fileSize.text = [NSString stringWithFormat:@"%@ : %0.2fKB",NSLocalizedString(@"Size",@""),[(NSString*)[fileInfo objectForKey:@"Size"] doubleValue]/1024];
    
    /*   self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(flipViews)];
     */
    UIView * customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,40,40)];
    [customView addSubview:self.navWebView];
    [customView addSubview:self.navFileView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
    
    
    //Request 
    
    
    
    self.urlRequest = [[self.fileInfo objectForKey:@"Link"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    self.filepathDic = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"filePathDic"]];
    
   /* if( self.filepathDic == nil){
        self.filepathDic = [NSMutableDictionary dictionary];
    }*/
    

   self.filePathURL = (NSURL*)[self.filepathDic objectForKey:self.urlRequest];
   
    
    if( self.filePathURL  == nil ){
    
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
        
        self.receivedData = [NSMutableData data];
        
        self.progressBar.hidden = false;
        
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlRequest]];
     
      
       self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    }else{
        
        self.filePathURL = [NSURL fileURLWithPath:(NSString*)self.filePathURL];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:self.filePathURL];
        [self.webView loadRequest:request];
       
      //  if(!isFlipped)
        //    [self flipViews];
        
        
    }
    
  

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self.connection cancel];
    [[NSUserDefaults standardUserDefaults] setObject:self.filepathDic forKey:@"filePathDic"];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    
    if(toInterfaceOrientation == UIInterfaceOrientationPortrait){
        isRotated = false;
    }else{
        isRotated = true;
    }
}

-(void) hideProgressHUD{
    [progressHUD hide:TRUE];
    progressHUD = nil;
}

-(void) initProgressHUD{
    progressHUD = [[MBProgressHUD alloc] initWithView:flipView];
    [flipView addSubview:progressHUD];
    
    progressHUD.labelText = NSLocalizedString(@"Loading...", @"");
    [progressHUD show:TRUE];
    
}

@end
